const db = require('../db/index')
const bcrypt = require('bcrypt')
//导入crypto库生成uuid
const crypto = require('crypto')
const { date } = require('joi')

//导入fs处理文件
fs = require('fs')

exports.uploadAvatar = (req, res) => {
    //生成唯一id
    const onlyId = crypto.randomUUID()
    let oldName = req.files[0].filename;
    let newName = Buffer.from(req.files[0].originalname, 'latin1').toString('utf8')
    fs.renameSync('./public/upload/' + oldName, './public/upload/' + newName)
    const sql = 'insert into image set ?'
    db.query(sql, {
        image_url: `http://127.0.0.1:3300/upoload/${newName}`,
        onlyId
    }, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            onlyId,
            status: 0,
            url: 'http://127.0.0.1:3300/upoload/${newName}'
        })
    })
}
//头像绑定账号
exports.bindAccount = (req, res) => {
    const {
        account,
        onlyId,
        url
    } = req.body
    //修改绑定image的唯一值的sql
    const sql = 'update image set account = ? where onlyId = ?'
    db.query(sql, [account, onlyId], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows == 1) {
            const usersql = 'update users set imgUrl = ? where account =?'
            db.query(usersql, [url, account], (err, results) => {
                if (err) return res.cc(err)
                res.send({
                    status: 0,
                    message: '修改成功'
                })
            })
        }
    })
}

// 获取用户信息 接收参数id
exports.getUserInfo = (req, res) => {
    const sql = 'select * from  users where id = ?'
    db.query(sql, req.body.id, (err, results) => {
        if (err) return res.cc(err)
        res.send(results)
    })
}




// 获取全部用户信息 
exports.getAllUserInfo = (req, res) => {
    const sql = 'select * from  users '
    db.query(sql, req.body.id, (err, results) => {
        if (err) return res.cc(err)
        res.send(results)
    })
}

//获取所有部门名称
exports.getAllDepartment = (req, res) => {
    const sql = 'select department from  department '
    db.query(sql, (err, results) => {
        if (err) return res.cc(err)
        res.send(results)
    })
}



//修改用户密码
exports.changeUserPassword = (req, res) => {
    const sql = 'select password from  users where id = ?'
    db.query(sql, req.body.id, (err, results) => {
        if (err) return res.cc(err)
        //比对库表中加密的密码和前端传值是否一致
        const compareResult = bcrypt.compareSync(req.body.oldPassword, results[0].password)
        if (!compareResult) {
            res.send({
                status: 1,
                message: '修改失败，原密码不正确'
            })
        }
        //对传来的密码进行加密
        req.body.newPassword = bcrypt.hashSync(req.body.newPassword, 10)
        const updatesql = 'update users set password = ? where id =?'
        db.query(updatesql, [req.body.newPassword, req.body.id], (err, results) => {
            if (err) return res.cc(err)
            res.send({
                satus: 0,
                message: '修改成功'
            })
        })

    })

}

//验证账户与邮箱是否一致  --忘记密码接口
exports.verifyAccountAndEmail = (req, res) => {
    const { account, email } = req.body
    const sql = 'select email,id from users where account = ?'
    db.query(sql, account, (err, results) => {
        if (err) return res.cc(err)
        if (results[0].email == email) {
            res.send({
                status: 0,
                message: '查询成功',
                id: results[0].id
            })
        } else {
            res.send({
                status: 1,
                message: '查询失败'
            })
        }
    })

}

// 修改密码
exports.changePasswordInLogin = (req, res) => {
    const user = req.body
    user.newPassword = bcrypt.hashSync(user.newPassword, 10)
    const sql = 'update users set password = ? where id = ?'
    db.query(sql, [user.newPassword, user.id], (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: '修改成功'
        })
    })

}

//插入用户信息
exports.setUserInfo = (req, res) => {
    const {
        account,
        password,
        name,
        identity,
        departerment,
        sex,
        email,
        satus,
    } = req.body
    //校验账号是否存在了
    findUserIsEmpty(account, name, results => {
        if (results > 0) {
            return res.cc('账户或姓名已经存在！', 0)
        } else {
            const insertsql = 'insert into users set  ?'
            const create_time = new Date()
            //对传来的密码加密
            const secretPassword = bcrypt.hashSync(password, 10)
            db.query(insertsql, {
                account: account,
                name: name,
                password: secretPassword,
                departerment: departerment,
                identity: identity,
                create_time: create_time,
                sex: sex,
                email: email,
                //初始默认状态 ，表示未冻结
                status: satus,
            }, (err, results) => {
                if (err) return res.cc(err)
                //如果插入成功/失败的回调  affectedRows 为影响到的行数，如果失败，行数不会超过1
                if (results.affectedRows !== 1) {
                    return res.send({
                        status: 1,
                        message: '添加用户失败,请重试'
                    })
                } else {
                    return res.send({
                        status: 0,
                        message: '添加用户成功!!'
                    })
                }
            })
        }

    })


}
//修改用户信息
//首先设计的思路为,前端可能不会修改全部的用户信息，只会修改个别的
exports.updateUserInfo = (req, res) => {
    const avaliableContent = req.body
    const updatesql = 'update users set ?  where id = ?'
    db.query(updatesql, [avaliableContent, avaliableContent.id], (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err)
        // 执行 SQL 语句成功，但影响行数不为 1
        if (results.affectedRows !== 1) return res.cc('修改用户基本信息失败！')
        // 修改用户信息成功
        return res.cc('修改用户基本信息成功！', 0)
    })

}

//删除用户 
exports.deleteUserInfo = (req, res) => {
    const avaliableContent = req.body
    findUserIsEmpty(avaliableContent.account, avaliableContent.name, results => {
        if (results > 0) {
            //执行删除语句
            const deletesql = 'delete from  users  where id = ?'
            db.query(deletesql, avaliableContent.id, (err, results) => {
                // 执行 SQL 语句失败
                if (err) return res.cc(err)

                // 执行 SQL 语句成功，但影响行数不为 1
                if (results.affectedRows !== 1) return res.cc('删除用户失败！')

                // 修改用户信息成功
                return res.cc('用户删除成功！', 0)
            })

        } else {
            return res.cc('用户不存在！', 0)
        }
    })

}
//通过部门id 查询员工
exports.getUserInfoBydepartmentId = (req, res) => {
    const query = req.body
    const updatesql = 'select * from users  where departmentId = ?'
    db.query(updatesql, query.id, (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err)
        res.send(results)

    })

}

//封装一个判断用户或名字是否存在的函数
const findUserIsEmpty = (account, name, callback) => {
    const selectsql = 'select * from users where account = ? or name = ?'
    //校验账号是否存在了
    db.query(selectsql, [account, name], (err, results) => {
        //query方法是异步调用，所以这里我们使用回调处理
        callback(results.length)
    })
}

